/*String.prototype.splice = function(idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};*/
import axios from "axios";
import { loginURL } from "../../config/env";
export default {
    __refreshToken : sessionStorage.getItem("refreshToken"),
    __interface : {
        'taskCronerAlertConfig': '/api/taskCronerAlertConfig',
        'taskAlertContact': '/api/taskAlertContact',
        'taskAlertInfo': '/api/taskAlertInfo',
        'taskAlertInfoNotify': '/api/taskAlertInfoNotify',
        'taskCronerConfig': '/api/taskCronerConfig',
        'taskCronerConfig/resetStats': '/api/taskCronerConfig/resetStats',
        'taskCronerLog': '/api/taskCronerLog',
        'taskHostConfig': '/api/taskHostConfig',
        'taskHostStatus': '/api/taskHostStatus',
        'taskHostStatu': '/api/taskHostStatu',
        'taskRunnerAlertConfig': '/api/taskRunnerAlertConfig',
        'taskRunnerConfig': '/api/taskRunnerConfig',
        'taskRunnerConfig/resetStats': '/api/taskRunnerConfig/resetStats',
        'taskRunnerLog': '/api/taskRunnerLog',
        'mscUser': '/admin/mscUser',
        'profile':'/admin/mscUser/profile',
        'modify':'/admin/mscUser/modify',
        'userRoles': '/admin/userRoles',
        'mscRole': '/admin/mscRole',
        'rolePerms': '/admin/rolePerms',
        'mscPerm': '/admin/mscPerm',
        'reset':'/admin/mscUser/reset'
    },
    refreshToken(self,callback) {
        let _this = this;
        axios.get(loginURL + '/api/auth/token',{
            headers: {'X-Authorization': 'Bearer '+_this.__refreshToken},
            params: {},
            validateStatus:function(status){
                return status >= 200 && status <500;//default
            }
        }).then((res) => {
            if(res.data.token){
                callback(res.data.token);
            }else{
                console.log("refreshToken");
                self.$router.push('/login');
            }

        });
    },
    getOtherAjax(self,_thisUrl,_params,callback) {
        let __token = sessionStorage.getItem("token");
        self.$axios.get(_thisUrl,{
            headers: {'X-Authorization': 'Bearer '+__token},
            params: _params,
            validateStatus:function(status){
                return status >= 200 && status <500;//default
            }
        }).then(callback);
    },
    getAjax(self,_thisUrl,pageSize,_params,callback) {
        let __token = sessionStorage.getItem("token");
        self.$axios.get(_thisUrl,{
            headers: {'X-Authorization': 'Bearer '+__token},
            params: {...{
                page:pageSize,
                resultNum:1000,
                orderBy:1
            },..._params},
            validateStatus:function(status){
                return status >= 200 && status <500;//default
            }
        }).then(callback);
    },
    getTableList(self,_thisUrl,pageSize,pageNum,_params,callback) {
        let _this = this;
        let __token = sessionStorage.getItem("token");
        __token !== null ? self.$axios.get(_this.__interface[_thisUrl]+'s',{
            headers: {'X-Authorization': 'Bearer '+__token},
            params: {...{
                page:pageSize,
                resultNum:pageNum,
                orderBy:2  //1：id正序 ， 2：id倒序 ，3：创建日期正序 ，4：创建日期倒序，5：计划执行时间正序 ，6：计划时间倒序（目前除了定时任务日志表具有 1，2，5,6四种排序，其他的都是1,2,3,4四种）
            },..._params},
            validateStatus:function(status){
                return status >= 200 && status <500;//default
            }
        }).then((res) => {
            if(res.data.status === 401){
                _this.refreshToken(self, (token) => {
                    sessionStorage.setItem("token",token);
                    self.getData(1,self.$store.state.allTable.pageSize);
                });
            }else{
                res.data.results ? res.data.results.forEach((v,i) => {
                    if(v.createDate) {
                        v.createDate = _this.formatDateTime(v.createDate);
                    }
                    if(v.sendedDate) {
                        v.sendedDate = _this.formatDateTime(v.sendedDate);
                    }
                    if(v.modifyDate) {
                        v.modifyDate = _this.formatDateTime(v.modifyDate);
                    }
                    if(v.nextRunDate) {
                        v.nextRunDate = _this.formatDateTime(v.nextRunDate);
                    }
                    if(v.statsStartDate) {
                        v.statsStartDate = _this.formatDateTime(v.statsStartDate);
                    }
                    if(v.nextDate) {
                        v.nextDate = _this.formatDateTime(v.nextDate);
                    }
                    if(v.runDate) {
                        v.runDate = _this.formatDateTime(v.runDate);
                    }
                    if(v.finishDate) {
                        v.finishDate = _this.formatDateTime(v.finishDate);
                    }
                    if(v.scheduleDate) {
                        v.scheduleDate = _this.formatDateTime(v.scheduleDate);
                    }
                    if(v.queueDate) {
                        v.queueDate = _this.formatDateTime(v.queueDate);
                    }
                    if(v.consumeDate) {
                        v.consumeDate = _this.formatDateTime(v.consumeDate);
                    }
                    if(v.lastUpdate) {
                        v.lastUpdate = _this.formatDateTime(v.lastUpdate);
                    }
                    if(v.ipStart) {
                        v.ipStart = _this.int2iP(v.ipStart);
                    }
                    if(v.ipEnd) {
                        v.ipEnd = _this.int2iP(v.ipEnd);
                    }
                    if(v.taskOwner && v.taskOwner !== '' && v.taskOwner[0] === '{') {
                        v.taskOwner=JSON.parse(v.taskOwner);
                    }else{
                        v.taskOwner='';
                    }
                    if(v.taskLink && v.taskLink !== '' && v.taskLink[0] === '{') {
                        v.taskLink=JSON.parse(v.taskLink);
                    }else{
                        v.taskLink='';
                    }
                    if(v.failAllRateLink && v.failAllRateLink !== '' && v.failAllRateLink[0] === '{') {
                        v.failAllRateLink=JSON.parse(v.failAllRateLink);
                    }else{
                        v.failAllRateLink='';
                    }
                    if(v.failConfigRateLink && v.failConfigRateLink !== '' && v.failConfigRateLink[0] === '{') {
                        v.failConfigRateLink=JSON.parse(v.failConfigRateLink);
                    }else{
                        v.failConfigRateLink='';
                    }
                    if(v.failPartnerRateLink && v.failPartnerRateLink !== '' && v.failPartnerRateLink[0] === '{') {
                        v.failPartnerRateLink=JSON.parse(v.failPartnerRateLink);
                    }else{
                        v.failPartnerRateLink='';
                    }
                    if(v.failProgramRateLink && v.failProgramRateLink !== '' && v.failProgramRateLink[0] === '{') {
                        v.failProgramRateLink=JSON.parse(v.failProgramRateLink);
                    }else{
                        v.failProgramRateLink='';
                    }
                }) : '';
                callback(res.data);
            }
        }).catch((res) => {
            // self.$router.push('/login');
        }) : self.$router.push('/login');
    },
    postTableList(self,_thisUrl,__ruleForm,callback,refresh) {
        let _this = this;
        let __token = sessionStorage.getItem("token");
        self.$axios.post(_this.__interface[_thisUrl],__ruleForm,{
            headers: {'X-Authorization': 'Bearer '+__token},
            validateStatus:function(status){
                return status >= 200 && status <500;//default
            }
        }).then((res) => {
            if(res.data.status === 401){
                _this.refreshToken(self, (token) => {
                    sessionStorage.setItem("token",token);
                    refresh ? refresh() : self.getData(1,self.$store.state.allTable.pageSize);
                });
            }else{
                callback();
            }
        }).catch((res) => {
            self.$router.push('/login');
        });
    },
    putTableList(self,_thisUrl,__ruleForm,callback) {
        let _this = this;
        const timeStr = "2017-05-18T05:59:14.841Z";
        let __token = sessionStorage.getItem("token");
        if(__ruleForm.createDate) {
            __ruleForm.createDate = timeStr;
        }
        if(__ruleForm.modifyDate) {
            __ruleForm.modifyDate = timeStr;
        }
        if(__ruleForm.nextRunDate) {
            __ruleForm.nextRunDate = timeStr;
        }
        if(__ruleForm.statsStartDate) {
            __ruleForm.statsStartDate = timeStr;
        }
        if(__ruleForm.nextDate) {
            __ruleForm.nextDate = timeStr;
        }
        if(__ruleForm.runDate) {
            __ruleForm.runDate = timeStr;
        }
        if(__ruleForm.finishDate) {
            __ruleForm.finishDate = timeStr;
        }
        if(__ruleForm.scheduleDate) {
            __ruleForm.scheduleDate = timeStr;
        }
        if(__ruleForm.queueDate) {
            __ruleForm.queueDate = timeStr;
        }
        if(__ruleForm.consumeDate) {
            __ruleForm.consumeDate = timeStr;
        }
        if(__ruleForm.lastUpdate) {
            __ruleForm.lastUpdate = timeStr;
        }
        self.$axios.put(_this.__interface[_thisUrl],__ruleForm,{
            headers: {'X-Authorization': 'Bearer '+__token},
            validateStatus:function(status){
                return status >= 200 && status <500;//default
            }
        }).then((res) => {
            if(res.data.status === 401){
                _this.refreshToken(self, (token) => {
                    sessionStorage.setItem("token",token);
                    self.addData('ruleForm');
                });
            }else{
                callback(res.data);
            }
        }).catch((res) => {
            // self.$router.push('/login');
        });
    },
    deleteTableList(self,_thisUrl,_id,callback) {
        let _this = this;
        let __token = sessionStorage.getItem("token");
        self.$confirm(self.$i18n.t('allTable.deleteTip'), self.$i18n.t('allTable.tip'), {
            confirmButtonText: self.$i18n.t('allTable.confirm'),
            cancelButtonText: self.$i18n.t('allTable.cancel'),
            type: 'warning'
        }).then(() => {
            self.$axios.delete(_this.__interface[_thisUrl]+'/'+_id,{
                headers: {'X-Authorization': 'Bearer '+__token},
                validateStatus:function(status){
                    return status >= 200 && status <500;//default
                }
            }).then((res) => {
                if(res.data.status === 401){
                    _this.refreshToken(self, (token) => {
                        sessionStorage.setItem("token",token);
                        self.getData(1,self.$store.state.allTable.pageSize);
                    });
                }else{
                    self.$message({
                        type: 'success',
                        message: self.$i18n.t('allTable.successDel')
                    });
                    callback();
                }
            }).catch((res) => {
                self.$router.push('/login');
            });
        }).catch(() => {
            self.$message({
                type: 'info',
                message: self.$i18n.t('allTable.cancelDel')
            });
        });
    },
    searchTableList(self,_thisUrl,_searchId,callback) {
        let _this = this;
        let __token = sessionStorage.getItem("token");
        self.$axios.get(_this.__interface[_thisUrl]+'/'+_searchId,{
            headers: {
                'X-Authorization': 'Bearer '+__token
            },
            validateStatus:function(status){
                return status >= 200 && status <500;//default
            }
        }).then((res) => {
            console.log(res.data);
            if(res.data && res.data !== ''){
                if(res.data.status === 401){
                    _this.refreshToken(self, (token) => {
                        sessionStorage.setItem("token",token);
                        self.getData(1,self.$store.state.allTable.pageSize);
                    });
                }
                else{
                    if(res.data.createDate) {
                        res.data.createDate = _this.formatDateTime(res.data.createDate);
                    }
                    if(res.data.sendedDate) {
                        res.data.sendedDate = _this.formatDateTime(res.data.sendedDate);
                    }
                    if(res.data.modifyDate) {
                        res.data.modifyDate = _this.formatDateTime(res.data.modifyDate);
                    }
                    if(res.data.nextRunDate) {
                        res.data.nextRunDate = _this.formatDateTime(res.data.nextRunDate);
                    }
                    if(res.data.statsStartDate) {
                        res.data.statsStartDate = _this.formatDateTime(res.data.statsStartDate);
                    }
                    if(res.data.nextDate) {
                        res.data.nextDate = _this.formatDateTime(res.data.nextDate);
                    }
                    if(res.data.runDate) {
                        res.data.runDate = _this.formatDateTime(res.data.runDate);
                    }
                    if(res.data.finishDate) {
                        res.data.finishDate = _this.formatDateTime(res.data.finishDate);
                    }
                    if(res.data.scheduleDate) {
                        res.data.scheduleDate = _this.formatDateTime(res.data.scheduleDate);
                    }
                    if(res.data.queueDate) {
                        res.data.queueDate = _this.formatDateTime(res.data.queueDate);
                    }
                    if(res.data.consumeDate) {
                        res.data.consumeDate = _this.formatDateTime(res.data.consumeDate);
                    }
                    if(res.data.lastUpdate) {
                        res.data.lastUpdate = _this.formatDateTime(res.data.lastUpdate);
                    }
                    if(res.data.ipStart) {
                        res.data.ipStart = _this.int2iP(res.data.ipStart);
                    }
                    if(res.data.ipEnd) {
                        res.data.ipEnd = _this.int2iP(res.data.ipEnd);
                    }
                    if(res.data.taskOwner && res.data.taskOwner !== '') {
                        res.data.taskOwner=JSON.parse(res.data.taskOwner);
                    }
                    if(res.data.taskLink && res.data.taskLink !== '' && res.data.taskLink[0] === '{') {
                        res.data.taskLink=JSON.parse(res.data.taskLink);
                    }
                    if(res.data.failAllRateLink && res.data.failAllRateLink !== '' && res.data.failAllRateLink[0] === '{') {
                        res.data.failAllRateLink=JSON.parse(res.data.failAllRateLink);
                    }
                    if(res.data.failConfigRateLink && res.data.failConfigRateLink !== '' && res.data.failConfigRateLink[0] === '{') {
                        res.data.failConfigRateLink=JSON.parse(res.data.failConfigRateLink);
                    }
                    if(res.data.failPartnerRateLink && res.data.failPartnerRateLink !== '' && res.data.failPartnerRateLink[0] === '{') {
                        res.data.failPartnerRateLink=JSON.parse(res.data.failPartnerRateLink);
                    }
                    if(res.data.failProgramRateLink && res.data.failProgramRateLink !== '' && res.data.failProgramRateLink[0] === '{') {
                        res.data.failProgramRateLink=JSON.parse(res.data.failProgramRateLink);
                    }
                    callback(res.data);
                }
            }else{
                self.$message.error(self.$i18n.t('allTable.nonExistent'));
                self.tableData = [];
            }

        }).catch((res) => {
            // self.$router.push('/login');
        });
    },
    formatDateTime(inputTime,format) {
        var date = new Date(inputTime);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? ('0' + minute) : minute;
        second = second < 10 ? ('0' + second) : second;
        if(format && format === 'ymd'){
            return y + '-' + m + '-' + d;
        }else{
            return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
        }

    },
    int2iP(num) {
        let str;
        let tt = new Array();
        tt[0] = (num >>> 24) >>> 0;
        tt[1] = ((num << 8) >>> 24) >>> 0;
        tt[2] = (num << 16) >>> 24;
        tt[3] = (num << 24) >>> 24;
        str = String(tt[0]) + "." + String(tt[1]) + "." + String(tt[2]) + "." + String(tt[3]);
        return str;
    },
    ip2int(ip) {
        var num = 0;
        ip = ip.split(".");
        num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]);
        num = num >>> 0;
        return num;
    },
    changePageGoToTop(self,val) {
        self.$nextTick(function () {
            document.querySelectorAll('.el-table__body-wrapper')[0].scrollTop = 0;
        });
        self.getData(val,self.$store.state.allTable.pageSize);
    }
}
